package com.aiguigu.lottery.user.mapper;

import com.aiguigu.lottery.common.entity.UserEntity;
import org.apache.ibatis.annotations.*;

/**
 * 用户Mapper接口 (对应 emp 表)
 */
@Mapper
public interface UserMapper {
    
    /**
     * 根据用户名查找用户
     */
    @Select("SELECT * FROM emp WHERE username = #{username}")
    UserEntity findByUsername(@Param("username") String username);
    
    /**
     * 根据ID查找用户
     */
    @Select("SELECT * FROM emp WHERE id = #{id}")
    UserEntity findById(@Param("id") Integer id);
    
    /**
     * 插入用户
     */
    @Insert("INSERT INTO emp (username, password, name, gender, phone, job, avatar, create_time, update_time, qq, address) " +
            "VALUES (#{username}, #{password}, #{name}, #{gender}, #{phone}, #{job}, #{avatar}, #{createTime}, #{updateTime}, #{qq}, #{address})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(UserEntity user);
    
    /**
     * 更新用户
     */
    @Update("UPDATE emp SET username = #{username}, password = #{password}, " +
            "name = #{name}, gender = #{gender}, phone = #{phone}, job = #{job}, " +
            "avatar = #{avatar}, update_time = #{updateTime}, qq = #{qq}, address = #{address} " +
            "WHERE id = #{id}")
    int update(UserEntity user);
    
    /**
     * 更新用户个人信息（不包括用户名和密码）
     */
    @Update("UPDATE emp SET name = #{name}, gender = #{gender}, phone = #{phone}, " +
            "avatar = #{avatar}, qq = #{qq}, address = #{address}, update_time = #{updateTime} " +
            "WHERE id = #{id}")
    int updateProfile(UserEntity user);
    
    /**
     * 删除用户
     */
    @Delete("DELETE FROM emp WHERE id = #{id}")
    int deleteById(@Param("id") Integer id);
    
    /**
     * 根据职位查找用户（管理员权限验证）
     */
    @Select("SELECT * FROM emp WHERE job = #{job}")
    java.util.List<UserEntity> findByJob(@Param("job") Integer job);
    
    /**
     * 验证用户是否为管理员（job=1）
     */
    @Select("SELECT COUNT(*) FROM emp WHERE id = #{userId} AND job = 1")
    int isAdmin(@Param("userId") Integer userId);
    
    /**
     * 查询所有用户
     */
    @Select("SELECT * FROM emp ORDER BY id")
    java.util.List<UserEntity> findAll();
    
    /**
     * 删除用户相关的中奖记录（处理外键约束）
     */
    @Delete("DELETE FROM prize_record WHERE user_id = #{userId}")
    int deletePrizeRecordsByUserId(@Param("userId") Integer userId);
}